import { AppTask, AppTaskQueue } from "./app.task.class";
import { Subject, timer } from "rxjs";
import { V3proSubjectMessage } from "./v3pro-task/model/v3pro.model";
import { V3proHeathCheckServer } from "./v3pro-task/v3pro.heath.check.server";
import { StarriverServer } from "./starriver-task/starriver.server";
import { appConfig } from "../configs/env.config.load";
import { logger } from "../configs/log.config";

/**
 * AppServer
 * 整个采集应用的顶层服务
 */
export class AppServer extends AppTask {
  __pause(): Promise<boolean> {
    return Promise.resolve(false);
  }

  __restore(): Promise<boolean> {
    return Promise.resolve(false);
  }

  /**
   * 全局消息订阅器
   * 1. 当采集任务计算出告警信息时，会通过该订阅器通知到所有订阅者
   * @private
   */
  private __subject = new Subject<V3proSubjectMessage>();

  /**
   * 任务队列，没卵用，只是方便启动
   * @private
   */
  private __tasks = new AppTaskQueue(100);

  /**
   * 启动服务
   * 1. 启动starriver推送任务
   * 2. 启动v3pro采集任务
   */
  async __run(): Promise<void> {
    this.__subject.subscribe(this.__subjectSubscribe.bind(this));
    this.__tasks.addTask(new StarriverServer(this.__subject));
    timer(appConfig.v3pro.collectTimer.delayOnStart * 1000).subscribe(
      this.__startDelayServers.bind(this),
    );
    await this.__await();
  }

  /**
   * 启动任务
   * @private
   */
  private __startDelayServers() {
    this.__tasks.addTask(new V3proHeathCheckServer(this.__subject));
  }

  /**
   * 订阅全局消息（没卵用，方便测试）
   * @param message
   * @private
   */
  private __subjectSubscribe(message: V3proSubjectMessage) {
    logger.info("collect message [%s]: [status] : %s", message.alertType, message.status);
  }

  __stop(): Promise<boolean> {
    return Promise.resolve(false);
  }
}
